import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';
import {
  StyleSheet,
  Text,
  View,
  SafeAreaView,
  TextInput,
  Pressable,
  processColor,
  Alert,
} from 'react-native';
import {
  goodsRealPrice,
  orderBet,
  goodsKLine,
  userAccount,
} from '../../api/index.js';
import {editUser} from '../../redux/actions/UserAction.js';
import {Picker} from '@react-native-picker/picker';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import {LineChart} from 'react-native-charts-wrapper';

const greenBlue = 'rgb(26, 182, 151)';
const petrel = 'rgb(59, 145, 153)';

const Bet = ({navigation, dispatch, user}) => {
  const [section, setSection] = useState('0.01');
  const [amount, setAmount] = useState('');

  const [profitPoint, setProfitPoint] = useState('');
  const [failPoint, setFailPoint] = useState('');

  const [data, setData] = useState({
    dataSets: [],
  });
  const [legend, setLegend] = useState();
  const [marker, setMarker] = useState({
    enabled: true,
    digits: 2,
    backgroundTint: processColor('teal'),
    markerColor: processColor('#F0C0FF8C'),
    textColor: processColor('white'),
  });
  const [xAxis, setXAxis] = useState({
    granularityEnabled: true,
    granularity: 1,
  });

  const [btcInfo, setBtcInfo] = useState({});

  const getDataLine = async function () {
    const res = await goodsKLine({
      symbol: 'BTC',
    });
    console.log('KLine', res);
    if (res.code === 1000) {
      const values = res.data.price.map((ele, index) => {
        return {
          y: parseFloat(ele),
          x: index,
          marker: ele,
        };
      });
      const obj = {
        dataSets: [
          {
            values: values,
            label: '',
            config: {
              mode: 'CUBIC_BEZIER',
              drawValues: false,
              lineWidth: 1,
              drawCircles: true,
              circleColor: processColor(petrel),
              drawCircleHole: false,
              circleRadius: 1,
              highlightColor: processColor('transparent'),
              color: processColor(petrel),
              drawFilled: true,
              fillGradient: {
                colors: [processColor('red'), processColor('yellow')],
                positions: [0, 0.5],
                angle: 90,
                orientation: 'TOP_BOTTOM',
              },
              fillAlpha: 1000,
              valueTextSize: 15,
            },
          },
        ],
      };
      setData(obj);
    }
  };
  const getData = async function () {
    const res = await goodsRealPrice({
      symbol: 'BTC',
    });
    if (res.code === 1000) {
      if (res.data.lastestPrice) {
        res.data.lastestPrice = parseFloat(res.data.lastestPrice);
      }
      if (res.data.quoteVolume) {
        const num = res.data.quoteVolume / 100000000;
        res.data.quoteVolumeTemp = num.toFixed(1);
      }
      setBtcInfo(res.data);
    }
  };
  const onAmountChange = value => {
    if (user.wallet && user.wallet.total) {
      const total = parseFloat(user.wallet.total);
      console.log(total);
      if (total >= value) {
        setAmount(value);
      } else {
        Alert.alert('提示', '金额不足');
      }
    } else {
    }
  };

  const doBet = async params => {
    console.log(params);
    const res = await orderBet(params);
    if (res.code === 1000) {
      const resAccount = await userAccount();
      await dispatch(editUser(resAccount.data));
      Alert.alert('提示', '投注成功');
    } else {
      Alert.alert('提示', res.msg);
    }
  };

  const doBetHandle = type => {
    if (!amount) {
      Alert.alert('提示', '请输入投注金额！');
      return;
    }
    const content = type === 1 ? '您是否确认做多？' : '您是否确认做空？';
    Alert.alert('提示', content, [
      {
        text: '確認',
        onPress: () => {
          doBet({
            symbol: 'BTC',
            goods_id: 1,
            section: section,
            amount: amount,
            type,
          });
        },
      },
      {
        text: '取消',
        onPress: () => console.log('Cancel Pressed'),
        style: 'cancel',
      },
    ]);
  };

  useEffect(() => {
    getData();
    getDataLine();
    const timer = setInterval(() => {
      getData();
    }, 3 * 1000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  useEffect(() => {
    if (btcInfo.lastestPrice && section) {
      const pp = (1 + section) * btcInfo.lastestPrice;
      const fp = (1 - section) * btcInfo.lastestPrice;

      setProfitPoint(pp.toFixed(2));
      setFailPoint(fp.toFixed(2));
    } else {
      setProfitPoint('');
      setFailPoint('');
    }
  }, [btcInfo, section]);
  return (
    <SafeAreaView>
      <View style={styles.container}>
        <View style={styles.top}>
          <View style={styles.topLeft}>
            <Text style={styles.topLeftText1}>{btcInfo.lastestPrice}</Text>
            <View style={styles.topLeftBottom}>
              <Text style={styles.topLeftText2}>≈ $564.33</Text>
              <Text style={styles.topLeftText3}>
                {btcInfo.priceChangePercent}%
              </Text>
            </View>
          </View>
          <View style={styles.topRight}>
            <View style={styles.topRightOne}>
              <Text style={styles.topRightOneText1}>24小时最高价</Text>
              <Text style={styles.topRightOneText2}>{btcInfo.highPrice}</Text>
              <Text style={styles.topRightOneText1}>24小时最低价</Text>
              <Text style={styles.topRightOneText2}>{btcInfo.lowPrice}</Text>
            </View>
            <View style={styles.topRightTwo}>
              <Text style={styles.topRightOneText1}>24小时成交量（BNB）</Text>
              <Text style={styles.topRightOneText2}>{btcInfo.volume}</Text>
              <Text style={styles.topRightOneText1}>24小时成交量（BUSD）</Text>
              <Text style={styles.topRightOneText2}>
                {btcInfo.quoteVolumeTemp}亿
              </Text>
            </View>
          </View>
        </View>
        <View style={styles.chartNav}>
          <View style={styles.chartNavLeft}>
            <Pressable style={styles.chartNavLeftItem}>
              <Text style={styles.chartNavLeftItemTextActive}>图表</Text>
            </Pressable>
            <Pressable style={styles.chartNavLeftItem}>
              <Text style={styles.chartNavLeftItemText}>15分</Text>
            </Pressable>
            <Pressable style={styles.chartNavLeftItem}>
              <Text style={styles.chartNavLeftItemText}>1小畤</Text>
            </Pressable>
            <Pressable style={styles.chartNavLeftItem}>
              <Text style={styles.chartNavLeftItemText}>4小时</Text>
            </Pressable>
            <Pressable style={styles.chartNavLeftItem}>
              <Text style={styles.chartNavLeftItemText}>1日</Text>
            </Pressable>
            <Pressable style={styles.chartNavLeftItem}>
              <Text style={styles.chartNavLeftItemText}>更多</Text>
            </Pressable>
          </View>
          <View style={styles.chartNavRight}>
            <Pressable style={styles.heartActive}>
              <MaterialCommunityIcons
                name="tune-variant"
                color="#8789A1"
                size={16}
              />
            </Pressable>
          </View>
        </View>
        <View style={styles.chartContainer}>
          <LineChart
            style={styles.chartContainer}
            data={data}
            chartDescription={{text: ''}}
            legend={legend}
            marker={marker}
            xAxis={xAxis}
            drawGridBackground={false}
            borderColor={processColor('teal')}
            borderWidth={1}
            drawBorders={true}
            autoScaleMinMaxEnabled={false}
            touchEnabled={true}
            dragEnabled={true}
            scaleEnabled={true}
            scaleXEnabled={true}
            scaleYEnabled={true}
            pinchZoom={true}
            doubleTapToZoomEnabled={true}
            highlightPerTapEnabled={true}
            highlightPerDragEnabled={false}
            // visibleRange={this.state.visibleRange}
            dragDecelerationEnabled={true}
            dragDecelerationFrictionCoef={0.99}
            keepPositionOnRotation={false}
          />
        </View>
        <View style={styles.operation}>
          <View style={styles.operationOne}>
            <View style={styles.operationOneLeft}>
              <Text style={styles.operationOneLeftText}>區間：</Text>
            </View>
            <View style={styles.operationOneRight}>
              <Picker
                selectedValue={section}
                style={styles.operationOneLeftPicker}
                onValueChange={(itemValue, itemIndex) => setSection(itemValue)}>
                <Picker.Item label="1.0%" value="0.01" />
                <Picker.Item label="2.0%" value="0.02" />
                <Picker.Item label="3.0%" value="0.03" />
              </Picker>
            </View>
          </View>
          <View style={styles.operationTwo}>
            <View style={styles.operationTwoLeft}>
              <Text style={styles.operationTwoLeftText}>投注金額：</Text>
            </View>
            <View style={styles.operationTwoLeft2}>
              <TextInput
                style={styles.sectionInput}
                keyboardType="number-pad"
                onChangeText={onAmountChange}
                value={amount}
              />
            </View>
            <View style={styles.operationTwoRight}>
              <Text style={styles.operationTwoRightText}>USDT</Text>
            </View>
          </View>
          <View style={styles.operationTwo}>
            <View style={styles.operationTwoLeft}>
              <Text style={styles.operationTwoLeftText} />
            </View>
            <View style={styles.operationTwoRight2}>
              <Text style={styles.operationTwoRight2Text}>USDT 可用餘額：</Text>
              <Text style={styles.operationTwoRight2Text2}>
                {user.wallet.total}
              </Text>
            </View>
          </View>
          <View style={styles.operationThree}>
            <View style={styles.operationThreeLeft}>
              <Pressable
                style={styles.operationThreeLeftButton}
                onPress={() => {
                  doBetHandle(2);
                }}>
                <Text style={styles.operationThreeLeftButtonText}>▼做空</Text>
              </Pressable>
              <Text style={styles.operationThreeLeftText1}>
                止損點：{profitPoint}
              </Text>
              <Text style={styles.operationThreeLeftText2}>
                獲利點：{failPoint}
              </Text>
            </View>
            <View style={styles.operationThreeRight}>
              <Pressable
                style={styles.operationThreeRightButton}
                onPress={() => {
                  doBetHandle(1);
                }}>
                <Text style={styles.operationThreeRightButtonText}>▲做多</Text>
              </Pressable>
              <Text style={styles.operationThreeRightText1}>
                止損點：{failPoint}
              </Text>
              <Text style={styles.operationThreeRightText2}>
                獲利點：{profitPoint}
              </Text>
            </View>
          </View>
        </View>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {},
  top: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    flexDirection: 'row',
    height: 80,
    paddingLeft: 10,
    paddingRight: 10,
    backgroundColor: 'white',
  },
  topLeft: {
    display: 'flex',
  },
  topLeftText1: {
    color: '#30B88A',
    fontSize: 20,
    fontWeight: 'bold',
    lineHeight: 30,
  },
  topLeftBottom: {
    color: '#30B88A',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    flexDirection: 'row',
  },
  topLeftText2: {
    color: '#000',
    lineHeight: 22,
  },
  topLeftText3: {
    color: 'red',
    lineHeight: 22,
    marginLeft: 5,
  },
  topRight: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    flexDirection: 'row',
  },
  topRightTwo: {
    marginLeft: 10,
  },

  topRightOneText1: {
    color: '#666',
    lineHeight: 18,
    fontSize: 12,
  },
  topRightOneText2: {
    color: '#000',
    lineHeight: 18,
  },
  chartNav: {
    height: 30,
    backgroundColor: 'white',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    flexDirection: 'row',
    paddingLeft: 10,
    paddingRight: 10,
    marginTop: 1,
  },
  chartNavLeft: {
    height: 30,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    flexDirection: 'row',
  },
  chartNavLeftItem: {
    marginRight: 10,
  },
  chartNavLeftItemText: {
    fontSize: 12,
    color: '#aaa',
  },
  chartNavLeftItemTextActive: {
    fontSize: 12,
    color: '#333',
  },
  chartContainer: {
    height: 200,
    backgroundColor: 'white',
    marginTop: 1,
  },
  operation: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: 30,
    paddingLeft: 10,
    paddingRight: 10,
    paddingTop: 10,
  },

  operationOne: {
    display: 'flex',
    flexDirection: 'row',
  },
  operationOneLeft: {
    width: 80,
    display: 'flex',
    alignItems: 'flex-end',
    justifyContent: 'center',
    marginRight: 10,
  },
  operationOneLeftText: {
    color: '#333333',
    fontWeight: 'bold',
    fontSize: 16,
  },
  operationOneRight: {
    borderColor: '#acacac',
    borderWidth: 1,
    backgroundColor: 'white',
  },
  operationOneLeftPicker: {
    width: 230,
    backgroundColor: 'white',
  },
  sectionInput: {
    height: 40,
    width: 232,
    borderColor: '#acacac',
    borderWidth: 1,
    backgroundColor: 'white',
  },
  operationTwo: {
    display: 'flex',
    flexDirection: 'row',
    marginTop: 10,
  },
  operationTwoLeft: {
    width: 80,
    display: 'flex',
    alignItems: 'flex-end',
    justifyContent: 'center',
    marginRight: 10,
  },
  operationTwoRight: {
    marginLeft: 5,
  },
  operationTwoLeftText: {
    color: '#333333',
    fontWeight: 'bold',
    fontSize: 16,
  },
  operationTwoRightText: {
    color: '#333333',
    fontWeight: 'bold',
    fontSize: 16,
    lineHeight: 40,
  },
  operationTwoRight2: {
    marginLeft: 5,
    display: 'flex',
    alignItems: 'flex-end',
    justifyContent: 'center',
    flexDirection: 'row',
  },
  operationTwoRight2Text: {
    color: '#333333',
    fontWeight: 'bold',
    fontSize: 16,
    lineHeight: 40,
  },
  operationTwoRight2Text2: {
    color: 'red',
    fontWeight: 'bold',
    fontSize: 16,
    lineHeight: 40,
  },
  operationThree: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection: 'row',
    marginTop: 15,
  },
  operationThreeLeftButton: {
    width: 124,
    height: 72,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection: 'row',
    backgroundColor: '#FF0000',
    borderRadius: 10,
    marginBottom: 10,
  },
  operationThreeLeftButtonText: {
    color: 'white',
    fontSize: 34,
  },
  operationThreeLeftText1: {
    color: '#009900',
    fontSize: 14,
    fontWeight: 'bold',
    lineHeight: 24,
  },
  operationThreeLeftText2: {
    color: 'red',
    fontSize: 14,
    fontWeight: 'bold',
    lineHeight: 24,
    marginTop: 2,
  },
  operationThreeRightButton: {
    width: 124,
    height: 72,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection: 'row',
    backgroundColor: '#009900',
    borderRadius: 10,
    marginBottom: 10,
  },
  operationThreeRightButtonText: {
    color: 'white',
    fontSize: 34,
  },
  operationThreeRightText1: {
    color: '#009900',
    fontSize: 14,
    fontWeight: 'bold',
    lineHeight: 24,
  },
  operationThreeRightText2: {
    color: 'red',
    fontSize: 14,
    fontWeight: 'bold',
    lineHeight: 24,
    marginTop: 2,
  },
  operationThreeRight: {
    marginLeft: 35,
  },

  red: {
    color: 'red',
  },
});

// 3. select函数
function select(state) {
  // state
  return {
    user: state.user,
  };
}

export default connect(select)(Bet);
